/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package astralmlprocessor;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;


/**
 *
 * @author age
 */
public class XSLTProcessor {
    
    // Controlar el establecimiento de saxon como transformer XSLT solo la primera vez
    private static boolean setProperty = false;
    
    public static String simpleTransform(String sourcePath, String xsltPath,
                                       String resultDir, String [] fil, String [] obs, String sep) {
        String result = "";
        
        if (!setProperty) {
            System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
            setProperty = true;
        }
        
        TransformerFactory tFactory = TransformerFactory.newInstance();
        try {
            Transformer transformer = tFactory.newTransformer(new StreamSource(new File(xsltPath)));
            
            transformer.setParameter("fil0", ( fil != null && fil.length > 0 ? fil[0] : "." ));
            transformer.setParameter("fil1", ( fil != null && fil.length > 1 ? fil[1] : "." ));
            transformer.setParameter("fil2", ( fil != null && fil.length > 2 ? fil[2] : "." ));
            transformer.setParameter("fil3", ( fil != null && fil.length > 3 ? fil[3] : "." ));
            transformer.setParameter("obs0", ( obs != null && obs.length > 0 ? obs[0] : "." ));
            transformer.setParameter("obs1", ( obs != null && obs.length > 1 ? obs[1] : "." ));
            transformer.setParameter("obs2", ( obs != null && obs.length > 2 ? obs[2] : "." ));
            transformer.setParameter("sep", sep);
            
            transformer.transform(new StreamSource(new File(sourcePath)),
                                  new StreamResult(new File(resultDir)));

            // Obtener texto fichero
            FileInputStream fstream = new FileInputStream(resultDir);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            
            String strLine;
            while ((strLine = br.readLine()) != null)   {
                result += strLine + "\n";
            }
            
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    }

    public static void main(String[] args) {
        System.out.println(simpleTransform("web/xslt-transform/astronomy.xml",
                        "web/xslt-transform/astronomy.xsl", "WebPages/xslt-transform/astronomy.txt", new String[]{}, new String[]{"AGE","PPS"}, "-"));
    }
}
